import React, { Component } from "react";
import { connect } from "react-redux";
import {deepFullCopy, messages} from "share/common";
import {Button, Checkbox, Form, Input, InputNumber, message, Radio, Select, Switch, Spin} from "antd";
import Priority from "components/template/priority";
import Chooser from "components/chooser";
import constants from "share/constants";
import errorMessage from "share/errorMessage";
import dataSource from '../beep-timer.data';
import beepTimerService from "../beep-timer.service";
import 'styles/setting/beep-timer/slide-content/remind-content.scss'

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const CheckboxGroup = Checkbox.Group;
const { targetOption, remindTypesOption, invoiceStatusOption, statusOptions } = dataSource;

@Form.create()
@connect(mapStateToProps)
class RemindContent extends Component {

  state = {
    loading: false,
    honestLoading: false,
    honestInfo: {},
    priority: this.props.info.id ? {
      levelCode: this.props.info.levelCode,
      levelOrgId: this.props.info.levelOrgId,
      levelOrgName: this.props.info.levelOrgName,
      companyOID: this.props.info.companyOID
    } : {
      levelCode: 'SET_OF_BOOK',
      levelOrgId: this.props.company.setOfBooksId,
      levelOrgName: this.props.company.setOfBooksName
    },
    contentTip: '',
  };

  type2Code = {
    'EXPENSE_REPORT': 'ExpenseReportNoticeTask',
    'EXPENSE_INVOICE': 'ExpenseReportPasteReceiptNoticeTask'
  };

  type2Placeholder = {
    'EXPENSE_REPORT': {
      title: messages('basic-13.key239')/*费用报销提醒*/,
      content: messages('basic-13.key222')/*请及时报销*/
    },
    'EXPENSE_INVOICE': {
      title: messages('basic-13.key240')/*报销单交票提醒*/,
      content: messages('basic-13.key132')/*需尽快交票*/
    }
  };

  componentDidMount() {
    const { id, params } = this.props.info;
    id && this.getHonestInfo(id);
    const paramsData = JSON.parse(params || '{}');
    const content = paramsData.content || this.type2Placeholder[this.props.type].content
    this.setState({
      contentTip: (!id || paramsData.target === 0) ?
        messages('basic-13.key127',{arg1: content})/*您有（费用发生日期）发生的费用，{arg1}*/ :
        messages('basic-13.key241',{arg1: content})/*（费用所属人姓名/工号）有（费用发生日期）发生的费用，{arg1}*/
    })
  };

  getHonestInfo = id => {
    this.setState({ honestLoading: true });
    beepTimerService.getHonestList(id)
      .then(res => {
        this.setState({honestInfo: res.data.id ? res.data : {}})
      })
      .finally(() => this.setState({ honestLoading: false }))
  };

  setTips = (e, type) => {
    const { getFieldValue } = this.props.form;
    const target = type === 'target' ? e.target.value : getFieldValue('target');
    const content = (type === 'target' ? getFieldValue('content') : e.target.value) || messages('basic-13.key222')/*请及时报销*/;
    this.setState({
      contentTip: target === 0 ?
        messages('basic-13.key127',{arg1: content})/*您有（费用发生日期）发生的费用，{arg1}*/ :
        messages('basic-13.key241',{arg1: content})/*（费用所属人姓名/工号）有（费用发生日期）发生的费用，{arg1}*/
    })
  };

  handleSave = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!values.priority || !values.priority.levelOrgId) {
          message.error(messages('basic-13.key220')/*请选择所属组织*/);
          return;
        }
        const { info, type } = this.props;
        let rejectType = [];
        let expenseStatus = deepFullCopy(values.status || []);
        expenseStatus.map((item, index) => {
          item.length > 4 ? rejectType.push(item.substr(4)) : rejectType.push('1000');
          expenseStatus[index] = item.substr(0, 4);
        });
        const { levelCode, levelOrgId, companyOID } = values.priority;
        let params = {
          levelCode,
          enabledFlag: values.enabledFlag,
          hour: parseInt(values.hour),
          code: this.type2Code[type]
        };
        if (levelCode === 'SET_OF_BOOK') {
          params.setOfBooksId = levelOrgId;
        } else {
          params.companyOID = companyOID;
        }
        let saveParamsData = {
          title: values.title,
          content: values.content,
          remindDay: values.remindDay,
          target: values.target,
          remindTypes: values.remindTypes,
          status: expenseStatus
        };
        if (type === 'EXPENSE_REPORT') {
          Object.assign(saveParamsData, {
            labels: values.labels && values.labels.map(item => item.id),
            invoiceStatus: values.invoiceStatus,
            rejectType: rejectType
          })
        }
        if (type === 'EXPENSE_INVOICE') {
          Object.assign(saveParamsData, {
            formOids: values.formOids && values.formOids.map(item => item.formOID)
          })
        }
        info.id && (params.id = info.id);
        params.params = JSON.stringify(saveParamsData);
        this.setState({ loading: true });
        beepTimerService.newBeepTimer(params)
          .then(res => {
            const conditionId = values.conditionId && values.conditionId[0] && values.conditionId[0].id;
            beepTimerService.saveHonestInfo({ taskId: info.id || res.data.rows.id, conditionId })
              .then(() => {
                message.success(messages('common.save.success',{arg1: ""})/*{arg1} 保存成功*/);
                this.props.close(true);
              })
              .catch(e => errorMessage(e.response))
              .finally(() => this.setState({ loading: false }))
          })
          .catch(e => {
            errorMessage(e.response);
            this.setState({ loading: false });
          })
      }
    })
  };

  render() {
    const { type, info, company, form: { getFieldDecorator, getFieldValue, setFieldsValue } } = this.props;
    const { loading, honestLoading, honestInfo, priority, contentTip } = this.state;
    const paramsData = JSON.parse(info.params || '{}');
    let hourOption = [];
    for (let i = 0; i <= 23; i++) {
      hourOption.push(<Option value={i + ''}>{i + ":00"}</Option>)
    }
    let honestExtraParams = {taskConfigCode: this.type2Code[type]};
    if (getFieldValue('priority') && getFieldValue('priority').levelOrgId) {
      const paramName = getFieldValue('priority').levelCode === 'SET_OF_BOOK' ? 'setOfBooksId' : 'companyId';
      honestExtraParams[paramName] = getFieldValue('priority').levelOrgId;
    }
    return (
      <div className="remind-content">
        <Form className="new-form remind-content-form">
          <FormItem label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator("enabledFlag", {
              valuePropName: "checked",
              initialValue: info.id ? info.enabledFlag : true
            })(
              <Switch />
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key9')/*所属组织*/}>
            {getFieldDecorator('priority', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key9')/*所属组织*/})/*{arg1} 不能为空*/
              }],
              initialValue: priority
            })(
              <Priority
                top='SET_OF_BOOK'
                defaultValue={priority}
                showLabel={false}
                showCompanyComponent={false}
                disabled={!!info.id}
                onChange={() => setFieldsValue({ conditionId: undefined })}
              />
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key12')/*提醒对象*/}</div>
          <FormItem label={messages('basic-13.key12')/*提醒对象*/}>
            {getFieldDecorator('target', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key12')/*提醒对象*/})/*{arg1} 不能为空*/
              }],
              initialValue: info.id ? paramsData.target : 0
            })(
              <RadioGroup options={targetOption} onChange={e => this.setTips(e, 'target')} />
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key15')/*消息内容*/}</div>
          <FormItem label={messages('basic-13.key16')/*消息标题*/}>
            {getFieldDecorator('title', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key16')/*消息标题*/})/*{arg1} 不能为空*/
              }, {
                max: 50,
                message: messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/
              }],
              initialValue: paramsData.title
            })(
              <Input placeholder={this.type2Placeholder[type].title} />
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key15')/*消息内容*/} extra={contentTip}>
            {getFieldDecorator('content', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key15')/*消息内容*/})/*{arg1} 不能为空*/
              }, {
                max: 100,
                message: messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/
              }],
              initialValue: paramsData.content
            })(
              <TextArea placeholder={this.type2Placeholder[type].content} onChange={this.setTips} />
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key18')/*消息触发*/}</div>
          <FormItem label={messages('basic-13.key34')/*提醒方式*/} className="checkbox-item">
            {getFieldDecorator('remindTypes', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key34')/*提醒方式*/})/*{arg1} 不能为空*/
              }],
              initialValue: info.id ? paramsData.remindTypes : []
            })(
              <CheckboxGroup options={remindTypesOption}/>
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key223')/*触发日期*/}>
            {type === 'EXPENSE_REPORT' ?
              messages('basic-13.key152')/*在费用发生日期*/ :
              messages('basic-13.key153')/*在报销单首个打印节点后*/}
            {getFieldDecorator('remindDay', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: info.id ? paramsData.remindDay : undefined
            })(
              <InputNumber step={1} min={1} max={999} precision={0} style={{ width: 100, margin: '0 5px' }} />
            )}
            {messages('basic-13.key154')/*天后提醒员工*/}
          </FormItem>
          <FormItem label={messages('basic-13.key233')/*触发时间*/} >
            {getFieldDecorator('hour', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: info.id ? info.hour + ':00' : "10:00"
            })(
              <Select placeholder={messages('common.select')/*请选择*/}>
                {hourOption}
              </Select>
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key224')/*附加规则*/}</div>
          <FormItem label={messages('basic-13.key242')/*信用规则*/}>
            {honestLoading ? <Spin size="small" /> : (
              getFieldDecorator('conditionId', {
                initialValue: honestInfo.id ? [{ id: honestInfo.id, ruleCondition: honestInfo.ruleCondition }] : undefined
              })(
                <Chooser
                  type="beer-honest"
                  single
                  valueKey="id"
                  labelKey="ruleCondition"
                  disabled={!(getFieldValue('priority') && getFieldValue('priority').levelOrgId)}
                  listExtraParams={honestExtraParams}
                />
              )
            )}
          </FormItem>
          {type === 'EXPENSE_REPORT' && (
            <div>
              <FormItem label={messages('basic-13.key243')/*费用标签*/}>
                {getFieldDecorator('labels', {
                  rules: [{
                    required: true,
                    message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key243')/*费用标签*/})/*{arg1} 不能为空*/
                  }],
                  initialValue: info.id ? paramsData.labels.map((id, index) => {
                    return {
                      id,
                      name: paramsData.labelsName && paramsData.labelsName[index]
                    }
                  }) : []
                })(
                  <Chooser
                    type="expense-labels"
                    valueKey="id"
                    labelKey="name"
                    listExtraParams={{ labelCategory: 2 }}
                  />
                )}
              </FormItem>
              <FormItem label={messages('basic-13.key244')/*费用报销状态*/} className="checkbox-item">
                {getFieldDecorator('invoiceStatus', {
                  rules: [{
                    required: true,
                    message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key244')/*费用报销状态*/})/*{arg1} 不能为空*/
                  }],
                  initialValue: info.id ? paramsData.invoiceStatus : []
                })(
                  <CheckboxGroup options={invoiceStatusOption}/>
                )}
              </FormItem>
            </div>
          )}
          {type === 'EXPENSE_INVOICE' && (
            <FormItem label={messages('basic-13.key142')/*适用单据*/}>
              {getFieldDecorator('formOids', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key142')/*适用单据*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.id ? paramsData.formOids.map((formOID, index) => {
                  return {
                    formOID,
                    formName: paramsData.formNameList && paramsData.formNameList[index]
                  }
                }) : []
              })(
                <Chooser
                  type="select_form"
                  valueKey="formOID"
                  labelKey="formName"
                  listExtraParams={{ formTypeList: [3001, 3002, 3003], companyOID: company.companyOID }}
                />
              )}
            </FormItem>
          )}
          {(type === 'EXPENSE_INVOICE' || (getFieldValue('invoiceStatus') || []).includes(1)) && (
            <FormItem label={messages('basic-13.key245')/*报销单状态*/} className="checkbox-item">
              {getFieldDecorator('status', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key245')/*报销单状态*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.id && paramsData.status ?
                  paramsData.status.map((item, index) => `${item}${item === '1001' ? paramsData.rejectType[index] : ''}`) : []
              })(
                <CheckboxGroup options={type === 'EXPENSE_INVOICE' ? statusOptions : [...constants.expenseStatus]} />
              )}
            </FormItem>
          )}
          <div className='slide-footer'>
            <Button
              type='primary'
              loading={loading}
              disabled={this.props.disabled}
              onClick={this.handleSave}
            >
              {messages('common.save')/*保存*/}
            </Button>
            <Button onClick={() => this.props.close()}>{messages('common.back')/*返回*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default RemindContent;
